<template>
  <div class="w-1/1">
    <el-image :src="url" :style="{ width: props.width, aspectRatio: props.ratio }" fit="scale-down">
      <template #error>
        <div
          @click="chooseUrl"
          class="h-1/1 w-1/1 flex flex-row justify-center border border-dashed border-[2px] border-[var(--el-color-primary-light-6)] cursor-pointer"
        >
          <div class="flex flex-col justify-center">
            <div class="text-center">
              <el-icon size="32" color="var(--el-color-primary-light-6)" class="m-auto">
                <Plus />
              </el-icon>
              <div class="text-[var(--el-color-primary-light-6)]">建议相册长宽比例为{{ props.ratio }}</div>
            </div>
          </div>
        </div>
      </template>
    </el-image>
    <el-button type="primary" link v-if="url !== ''" @click="chooseUrl">重新选择</el-button>
    <UploadCool ref="sucaiRef" :fileType="props.filter" :maxSelect="1" @confirm="confirm"></UploadCool>
  </div>
</template>

<script setup lang="ts">
import { Plus } from "@element-plus/icons-vue";
import { ref, watch } from "vue";
import { ElMessage } from "element-plus";
import UploadCool from "@/components/UploadCool/index.vue";

const sucaiRef = ref<InstanceType<typeof UploadCool> | null>();

interface Props {
  url: string;
  width: string;
  filter: string;
  ratio: string;
  disabled: boolean;
}

const url = ref("");

const props = withDefaults(defineProps<Props>(), { url: "", width: "100%", filter: "", ratio: "25/18", disabled: true });

watch(
  () => props.url,
  () => {
    url.value = props.url;
  },
  { immediate: true }
);

watch(
  () => props.filter,
  () => {
    console.log(props.filter);
  },
  { immediate: true, deep: true }
);

const chooseUrl = () => {
  if (props.disabled) return ElMessage.warning("请先选择相册分类");
  sucaiRef.value?.change();
};

const confirm = (val: any) => {
  if (props.disabled) return ElMessage.warning("请先选择相册分类");
  if (val.cover) {
    url.value = val[0].cover;
  } else {
    url.value = val[0].origin_name;
  }
  emits("get-url", val[0]);
};

const emits = defineEmits(["get-url"]);
</script>

<style></style>
